<?php
header('Content-Type:text/html;charset=utf-8');
$from = $_GET['from']?trim($_GET['from']):'';
$tid = $_GET['tid']?trim($_GET['tid']):'';
$date = split(',', $_GET['date']?trim($_GET['date']):'');

$gt = new grubTicket($from, $tid, $date);
$gt->setMail('icyleaf.cn@gmail.com', '最新车票信息');
$gt->grub();

/**
 * Grub Tickets form piao.kuxun.com
 *
 * @author icyleaf <icyleaf.cn@gmail.com>
 * @copyright 2008 icyleaf, all rights reserved
 * @version 0.5
 * @license GNU Lesser GPL
 * @link http://icyleaf.com/
 */
class grubTicket {
	
	private $from = '';
	private $id = '';
	private $date = array();
	private $url_content = '';
	private $lastest = '';
	
	private $to = '';
	private $subject = '';
	private $mail_content = '';
	
	/**
	 * Initialize grubTicket Class
	 * @param (string) $from: From city name.
	 * @param (string) $id: Arrival city name or Train id.
	 * @param (string/array) $date: Train depart time - format: (M)M-DD.
	 */
	public function grubTicket($from, $id, $date='')
	{
		$this->from = trim($from);
		$this->id = trim($id);
		
		if ( !empty($date) )
		{
			if( is_array($date) )
			{
				foreach( $date as $item )
				{			
					if ( preg_match('/\d{1,2}-\d{1,2}/', $item) )
					{
						list($month, $day) = split('-', $item);
						$item = $month.'月'.$day.'日';
						array_push($this->date, $item);
					}
				}	
			}
			else
			{
				if ( preg_match('/\d{1,2}-\d{1,2}/', $date) )
				{
					list($month, $day) = split('-', $date);
					$date = $month.'月'.$day.'日';
					array_push($this->date, $date);
				}
			}
		}
		$url = "http://piao.kuxun.cn/search?T=Ticket&Cat=sale&From={$this->from}&q={$this->id}&x=0&y=0";
		
		$this->url_content = $this->getContent($url);
	}
	
	/**
	 * show lastest update informations.
	 */
	public function lastest()
	{
		$preg = '/<li class="c4">(.*)<\/li>/';
		preg_match($preg, $this->url_content, $match);
		list($date, $ago) = split(' ', $match[1]);
		$this->lastest = $ago;
		echo "最新更新时间：{$ago}<br />";
	}
	
	/**
	 * check update from 
	 */
	private function checkUpdate()
	{
		if ( !isset($_COOKIE['lastest']))
		{
			$this->sendMail();
		}
		else if ( isset($_COOKIE['lastest']) && $_COOKIE['lastest'] != $this->lastest )
		{
			$this->sendMail();
		}
		
		setcookie('lastest', $this->lastest);
	}
	
	/**
	 * grub ticket
	 * @param (boolean) $lastest: enable/disable to show update informations - default is TRUE.
	 */
	public function grub()
	{
		$preg = '/<a onclick="return clickTicket\(\'(.*)\', \'(.*)\', \'(.*)\', \'(.*)\'\);"/';
		preg_match_all($preg, $this->url_content, $match);
		// $match result:
		// 0. All preg string
		// 1. Train id
		// 2. Ticket type
		// 3. Train depart time
		// 4. Train links
		// TODO: debug
		//echo $this->url_content;
		//print_r($match);
		//return;
		
		if ( sizeof($match[0])<=0 )
		{
			echo '没有或无法抓取到搜索的信息';
			return;
		}
		echo $this->lastest();
		
		if ( sizeof($this->date)>0 )
		{
			$this->mail_content = '';
			for($i=0;$i<sizeof($match[3]);$i++)
			{
				foreach( $this->date as $item )
				{
					if( trim($match[3][$i])==$item )
					{
						$match[1][$i] = empty($match[1][$i])?'[未说明车次]':$match[1][$i];
						$this->mail_content .= $match[1][$i].' - '.$match[2][$i].' - '.$match[3][$i].
							' (<a href="'.$match[4][$i].'" target="_blank">车票信息</a>)<br />';
					}
				}
			}
			echo $this->mail_content;
			// check update if change, send mail as soon as possible.
			$this->checkUpdate();
		}
		else
		{
			// debug output.
			//print_r($match);
			for($i=0;$i<sizeof($match[3]);$i++)
			{
				$match[1][$i] = empty($match[1][$i])?'[未说明车次]':$match[1][$i];
				echo $i.': '.$match[1][$i].' - '.$match[2][$i].' - '.$match[3][$i].
					' (<a href="'.$match[4][$i].'" target="_blank">车票信息</a>)<br />';
			}
		}
	}
	
	public function render($content){
		//关闭缓存
		ob_end_flush();
		//ie下 需要先发送256个字节
		echo str_repeat(" ",256); 
		
		set_time_limit(0);
		
		for($i=0;$i<10;$i++){
			echo "Now Index is :". $i."<br>";
			flush();
			sleep(5);
		}
	}
	
	/**
	 * set email information
	 * @param (string) $to: email address where send to.
	 * @param (string) $subject: email subject - default is "Lastest ticket informations".
	 */
	public function setMail($to, $subject='Lastest ticket informations')
	{
		$this->to = trim($to);
		$this->subject = trim($subject);
	}

	/**
	 * send mail
	 * @param (string) $to: email address where send to.
	 * @param (string) $subject: email subject.
	 * @param (string) $content: email content.
	 * @return (boolean) mail send result.
	 */
	private function sendMail()
	{
		if ( empty($this->to) ) return 'Email地址为空';

		$headers = 'From: noreply@gmail.com'."\r\n".
			'Reply-To: noreply@gmail.com'."\r\n".
			'X-Mailer: PHP/'.phpversion()."\r\n".
			'Content-type:text/html;charset=utf-8'."\r\n";
		
		if ( mail($this->to, $this->subject, $this->mail_content, $headers) )
			return TRUE;
		else 
			return FALSE;
	}

	/**
	 * get remote webpage content
	 * @param (string) $url.
	 * @return (string) content of url.
	 */ 
	private function getContent($url)
	{
		$ch = curl_init();
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
		ob_start();
		curl_exec ($ch);
		curl_close ($ch);
		$content = ob_get_contents();
		ob_end_clean();
		
		return $content;
	}
}
?>